﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.BasicBase.BLL;
using Yipusoft.SoldierArchives.BLL;
using System.Web.UI.DataVisualization.Charting;
using System.Collections;
using System.Text;
using SmartWeb;
using System.Drawing;
using System.Data;

public partial class Police_Question_AnswerAnlyse : System.Web.UI.Page
{
    private string[] charts = { "Column", "Spline", "StepLine", "Spline" };
    int popedom = -1;
    Question2DataContext db = new Question2DataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        //权限

        if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "400201"))//总队
        {
            popedom = 0;
        }
        else if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "400202"))//支队
        {
            popedom = 1;
        }
        else if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "400203"))//中队
        {
            popedom = 2;
        }
        else
        {
            Response.Write("<script>alert('没有权限！');history.back(0);</script>");
            return;
        }
        if (!IsPostBack)
        {
            init();
        }
    }

    private void init()
    {


        string departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        if (Request.QueryString["ID"] != null)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Id", typeof(Guid)));
            dt.Columns.Add(new DataColumn("Name"));
            dt.Columns.Add(new DataColumn("No"));
            dt.Columns.Add(new DataColumn("SodierCount", typeof(int)));
            dt.Columns.Add(new DataColumn("state", typeof(int)));
            dt.Columns.Add(new DataColumn("age", typeof(decimal)));
            dt.Columns.Add(new DataColumn("GuardCount", typeof(decimal)));

            Guid sid = new Guid(Request["ID"]);
            List<SecurityProblem2> problemList = db.SecurityProblem2.Where(o => o.Sid == new Guid(Request.QueryString["ID"])).ToList();

           

            for (int i = 0; i < problemList.Count; i++)
            {
                DataRow dr = dt.NewRow();
               

                string c = SmartWeb.BLL.UserFun.getMarker(i + 1);

                SecurityProblem2 problem = problemList[i];
                dr["Id"] = problem.Id;
                dr["No"] = c;
                int sodierCount = GetSodierCount(sid, problem.Id);
               dr["sodierCount"] = sodierCount;

                dr["Name"] = problemList[i].Title;
                decimal age = 0;
                decimal sum = sodierCount * getMaxMark(problem);
                if (sum == 0)
                {
                    dr["age"] = 0;
                    dr["state"] = 3;
                   
                }
                else
                {
                     age = GetSumScore(sid, problem.Id) / sum;
                    dr["age"] = age;
                    
                }

               
                 dr["GuardCount"] = problem.GuardCount / 100;
               
                dr["state"] = 0;
                if (problem.GuardCount / 100 <= age)
                {
                    dr["state"] = 1;
                    
                }
                else if (Convert.ToInt32(dr["state"]) != 3)
                {
                    dr["state"] = 2;
                }
                dt.Rows.Add(dr);
            }

            UserChart.ChartAreas["Chart1"].AxisX.IsLabelAutoFit = false;
            UserChart.Series["未超出警戒线"].LabelFormat = "0.0" + "%";

            SecuritySubject2 subject = db.SecuritySubject2.Where(o => o.Id == sid).FirstOrDefault<SecuritySubject2>();
            UserChart.Titles[0].Text = subject.Caption + "--问题得分百分比";

            DataView dv = dt.DefaultView;
            dv.Sort = " age desc ";
            UserChart.Series["未超出警戒线"].Points.DataBindXY(dv, "No", dt.DefaultView, "age");
            UserChart.Series["警戒线"].Points.DataBindXY(dv, "No", dt.DefaultView, "GuardCount");


            for (int i = 0; i < dv.Count; i++)
            {
                if (popedom == 0)
                {

                    UserChart.Series["未超出警戒线"].Points[i].Url = "Analyse.aspx?ID=" + dv[i]["Id"] + "&Sid=" + Request["ID"];
                }
                else if (popedom == 1)
                {
                    UserChart.Series["未超出警戒线"].Points[i].Url = "view.aspx?ID=" + dv[i]["Id"] + "&Departmentid=" + departmentid.Substring(0, 4) + "&sid=" + Request["ID"];
                }
                else
                {
                    UserChart.Series["未超出警戒线"].Points[i].Url = "";
                }

                if (Convert.ToDecimal(dv[i]["age"]) >= Convert.ToDecimal(dv[i]["GuardCount"]))
                {
                    UserChart.Series["未超出警戒线"].Points[i].Color = Color.FromArgb(200, 0, 0);
                }
            }

            List<problem> problems = new List<problem>();
            foreach (DataRow dr in dt.Rows)
            {
                problems.Add(new problem { age = Convert.ToDecimal(dr["age"]), Name = dr["Name"].ToString(), No = dr["No"].ToString(), SodierCount = Convert.ToInt32(dr["SodierCount"]), state = Convert.ToInt32(dr["state"]) });
            }

            //UserGrid.DataSource = problemList;
            //UserGrid.DataBind();

            List<problem> ps = problems.Where(o => o.state == 1).OrderBy(o => o.No).OrderByDescending(o => o.age).ToList();
            DataList1.DataSource = ps;
            DataList1.DataBind();
            DataList1.Caption = "<span style='color:#C80000'>超出警戒线</span>";

            DataList2.DataSource = problems.Where(o => o.state == 2).OrderByDescending(o => o.age).OrderBy(o => o.No).OrderByDescending(o => o.age).ToList();
            DataList2.DataBind();
            DataList2.Caption = "<span style='color:#418CF0'>未超出警戒线</span>";

            DataList3.DataSource = problems.Where(o => o.state == 3).OrderByDescending(o => o.age).OrderBy(o => o.No).OrderByDescending(o => o.age).ToList();
            DataList3.DataBind();
        }

    }

    /// <summary>
    /// User defined sorting order logic
    /// </summary>
    public class MyComparer : IComparer
    {
        // This function should return a value less than zero if the first object is less than the second,
        //  zero if they are equal and a value greater than zero if the first object is greater than the second
        public int Compare(object a, object b)
        {
            DataPoint pointA = (DataPoint)a;
            DataPoint pointB = (DataPoint)b;

            // Compare axis labels first
            int result = pointA.AxisLabel.CompareTo(pointB.AxisLabel);

            // If axis labels are equal - compare Y values
            if (result == 0)
            {
                result = pointA.YValues[0].CompareTo(pointB.YValues[0]);
            }

            return result;
        }

        #region IComparer 成员

        int IComparer.Compare(object x, object y)
        {
            throw new NotImplementedException();
        }

        #endregion
    }


    public int GetSodierCount(Guid Sid, Guid Pid)
    {
        string Departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        Question2DataContext db = new Question2DataContext();
        int pp;
        if (popedom == 0)
        {
            pp = (from cc in db.SecurityResult2 where cc.Sid == Sid && cc.Pid == Pid group cc by cc.SoldierID into aa select aa).Count();

        }
        else if (popedom == 1)
        {
            pp = (from cc in db.SecurityResult2 where cc.Sid == Sid && cc.Pid == Pid && cc.SetDepartment.Substring(0, 4) == Departmentid.Substring(0, 4) group cc by cc.SoldierID into aa select aa).Count();

        }
        else if (popedom == 2)
        {
            pp = (from cc in db.SecurityResult2 where cc.Sid == Sid && cc.Pid == Pid && cc.SetDepartment == Departmentid group cc by cc.SoldierID into aa select aa).Count();

        }
        else
        {
            pp = 0;
        }
        return pp;
    }

    public decimal GetSumScore(Guid sid, Guid pid)
    {
        string Departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        decimal? pp = 0;
        Question2DataContext db = new Question2DataContext();
        if (popedom == 0)
        {
            pp = (from aa in db.SecurityResult2 where aa.Sid == sid && aa.Pid == pid select aa.Score).Sum();
        }
        else if (popedom == 1)
        {
            pp = (from aa in db.SecurityResult2 where aa.Sid == sid && aa.Pid == pid && aa.SetDepartment.Substring(0, 4) == Departmentid.Substring(0, 4) select aa.Score).Sum();

        }
        else if (popedom == 2)
        {
            pp = (from aa in db.SecurityResult2 where aa.Sid == sid && aa.Pid == pid && aa.SetDepartment == Departmentid select aa.Score).Sum();
        }




        if (pp.HasValue)
        {
            return pp.Value;
        }
        else
        {
            return 0;
        }
    }

    public decimal getMaxMark(SecurityProblem2 problem)
    {
        decimal? result = 0;
        if (problem.IsMultiple == 1)
        {
            var pp = (from aa in db.SecurityOption2 where aa.PId == problem.Id select aa.Mark).Sum();
            result = pp;
        }
        else
        {
            var pp = (from aa in db.SecurityOption2 where aa.PId == problem.Id select aa.Mark).Max();
            result = pp;
        }
        if (result.HasValue)
        {
            return result.Value;
        }
        else
        {
            return 0;
        }
    }






    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            problem problem = e.Item.DataItem as problem;
            Label lblTitle = (Label)e.Item.FindControl("lblTitle");
            lblTitle.Text = problem.No.ToString() + "、" + problem.Name + "&nbsp;&nbsp;(答题人数：" + problem.SodierCount + ")";
        }
    }

    class problem
    {
        public string Name;
        public string No;
        public int SodierCount;
        public int state;
        public decimal age;
    }
}
